import { EventEmitter, Injectable } from '@angular/core';
import { GraphBase } from './GraphBase';
import { GraphConfigService, OptionSetting, PluginSetting } from './graph-config.service';
import { ScenarioMetaService } from './scenario-meta.service';
import { Graph, Node } from '@antv/x6';
import { ScenarioConfig, CellConfig, NotifyFieldUpdated } from '../models';

@Injectable()
export class MonitorGraphUtilService extends GraphBase {

  scenario!: ScenarioConfig;
  nodeselected: EventEmitter<Node | undefined> = new EventEmitter();
  cellselected: EventEmitter<CellConfig> = new EventEmitter();

  constructor(service: GraphConfigService,
    private metaService: ScenarioMetaService
  ) {
    super(service);
  }

  protected override initGraph(): void {
    this.graph = new Graph({
      ...this.service.getGraphOptions(this._getOptionSetting()),
      moveThreshold: 10000,
      autoResize: this.container,
      container: this.container,
    });
  }
  protected override registers(): void {

  }
  protected override getPluginSetting(): Partial<PluginSetting> {
    return {
      selecton: true
    };
  }

  protected override bindKeys(): void {
    const { graph } = this;
    graph.on("node:click", ({ node }) => {
      const cfg = this._getCellConfig(node);
      if (cfg) {
        cfg.Type = node.data.category;
        this.cellselected.emit(cfg);
      }
    });
    graph.on("node:unselected", (e) => {
      this.nodeselected.emit(undefined);
    });
  }
  protected _getCellConfig(node: Node): CellConfig | undefined {
    switch (node.data.category) {
      case "Pipline":
        return this.scenario?.Lines?.find(a => a.Id == node.id);
        break;
      case "Site":
        return this.scenario?.Lines?.find(a => a.Id == node.parent?.id)?.Sites.find(a => a.Id == node.id);
        break;
      case "Srm":
        return this.scenario?.Srms?.find(a => a.Id == node.id);
        break;
    }
    return undefined;
  }

  private _getOptionSetting(): Partial<OptionSetting> {
    return {
      background: true,
      grid: true,
      panning: true,
      mousewheel: true,
      // connecting: true,
      highlighting: true,
    };
  }

  loadScenario(cfg: ScenarioConfig) {
    this.scenario = cfg;
    this.metaService.loadScenario(this.graph, cfg);
  }
  onFieldUpdated(data: NotifyFieldUpdated) {
    // const node = this.graph.getNodes().find(a => a.id == data.TargetId);
    // const d = node?.getData();
    // const t = { "category": "Site", "title": "Site1", "fields": [{ "Id": "c92a046d-603a-4b34-a76e-29a89f0de2bd", "Name": "Status", "Description": "点位状态", "Address": "DB1.860", "Type": "Int16" }, { "Id": "4a1e70de-8199-4138-981e-9c7ed9072fbd", "Name": "Barcode", "Address": "DB1.468", "Type": "String" }] };
    // for (const key in data.Value) {
    //   if (Object.prototype.hasOwnProperty.call(data.Value, key)) {
    //     const val = data.Value[key];     
        
    //   }
    // }
    // node?.setData({...d}, { deep: false });
  }
}
